package com.boyuan.aboutcase;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.core.AsyncTask;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.boyuan.huijiaoyu.R;
import com.boyuan.huijiaoyu.UploadFileActivity;
import com.magicsoft.app.entity.AttachmentEntity;
import com.magicsoft.app.entity.CaseDetailEntity;
import com.magicsoft.app.wcf.CaseService;
import com.magicsoft.app.wcf.listener.PostRecordResponseListener;
import com.magicsoft.constant.Constant;
import com.ttcaca.cas.android.client.utils.Helper;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass.
 * 
 */
public class AttachmentFragment extends Fragment implements OnClickListener {
	private static final int FILE_SELECT_CODE = 1014;
	private String id;
	private String realname;
	private String caseID;
	private MyReceiver myReceiver;
	private MyGridView listview;
	private MyAdapter adapter;
	private CaseService caseService;
	private ProgressDialog mDialog;
	private List<AttachmentEntity> attchlist = new ArrayList<AttachmentEntity>();
	private List<AttachmentEntity> attchlist2 = new ArrayList<AttachmentEntity>();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		View view = inflater.inflate(R.layout.fragment_attachment, container,
				false);
		initUI(view);
		return view;
	}

	private void initUI(View view) {
		SharedPreferences sp = getActivity().getSharedPreferences("a.xml", 0);
		view.findViewById(R.id.rela_upload).setOnClickListener(this);
		id = sp.getString("id", "");
		realname = sp.getString("realname", "");
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.GETATTACH);
		myReceiver = new MyReceiver();
		getActivity().registerReceiver(myReceiver, filter);
		initListview(view);
		registerForContextMenu(listview);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.add(0, 0, 0, "下载");
		menu.add(0, 1, 0, "删除");
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item
				.getMenuInfo();
		int position = menuInfo.position;
		String file_id = attchlist.get(position).getId();
		final String url = attchlist.get(position).getUrl();
		String fileName = attchlist.get(position).getName();
		String creater_id = attchlist.get(position).getCreater_id();
		switch (item.getItemId()) {
		case 0:
			// 下载
			// new Thread(new Runnable() {
			//
			// @Override
			// public void run() {
			// }
			//
			// }).start();
			downLoadFile(url,fileName);
			break;
		case 1:
			// 删除
			if(id.equals(creater_id)){
				deleFile(caseID, file_id);
			}else{
				Toast.makeText(getActivity(), "无法删除非自己上传的附件！", Toast.LENGTH_SHORT).show();
			}
			break;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}

	private void downLoadFile(String url, String filename) {
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			Toast t = Toast
					.makeText(getActivity(), "需要SD卡。", Toast.LENGTH_LONG);
			t.setGravity(Gravity.CENTER, 0, 0);
			t.show();
			return;
		}

		DownloaderTask task;
		task = new DownloaderTask(filename);
		task.execute(url);
	}

	// private void downLoadFile(String url) {
	// try {
	// URL url2 = new URL(url);
	// URLConnection openConnection = url2.openConnection();
	// InputStream inputStream = openConnection.getInputStream();
	// BufferedInputStream bis = new BufferedInputStream(inputStream);
	// ByteArrayBuffer baf = new ByteArrayBuffer(50);
	// int current = 0;
	// while((current = bis.read()) != -1){
	// baf.append((byte)current);
	// }
	// String str = EncodingUtils.getString(baf.toByteArray(), "UTF-8");
	// Log.e("下载的文件", "下载的文件是："+str);
	// } catch (MalformedURLException e) {
	// e.printStackTrace();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }

	private class DownloaderTask extends AsyncTask<String, Void, String> {

		private String fileName;

		public DownloaderTask() {

		}

		public DownloaderTask(String fileName) {
			this.fileName = fileName;
		}

		@Override
		protected String doInBackground(String... params) {
			String url = params[0];
			if (fileName == null || fileName.equals("")) {
				fileName = Helper.getReallyFileName(url);
			}
			Log.e("tag", "fileName=" + fileName);
			InputStream input = null;
			try {
				URL fileUrl = new URL(url);
				HttpURLConnection conn = (HttpURLConnection) fileUrl
						.openConnection();
				if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
					Log.e("tag", "错误提示" );
					return null;
				}
				input = conn.getInputStream();

				Helper.writeToDownload(fileName, input);
				return fileName;

			} catch (Exception e) {
				Log.e("doInBackground", "e = "+e.getMessage());
				e.printStackTrace();
				return null;
			} finally {
				if (input != null) {
					try {
						input.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			closeProgressDialog();
			if (result == null) {
				Toast t = Toast.makeText(getActivity(), "连接错误！请稍后再试！",
						Toast.LENGTH_LONG);
				t.setGravity(Gravity.CENTER, 0, 0);
				t.show();
				return;
			}

			Toast t = Toast.makeText(getActivity(), "已保存到SD卡。",
					Toast.LENGTH_LONG);
			t.setGravity(Gravity.CENTER, 0, 0);
			t.show();

			// 下载完成后调用第三方打开
			// File directory = new
			// File(Environment.getExternalStorageDirectory()
			// + "/colourlife/download/");
			// // File directory = Environment.getExternalStorageDirectory();
			// File file = new File(directory, result);
			// Log.i("tag", "Path=" + file.getAbsolutePath());
			// Intent intent = getFileIntent(file);
			// startActivity(intent);

		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			showProgressDialog();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

	}

	private void showProgressDialog() {
		if (mDialog == null) {
			mDialog = new ProgressDialog(getActivity());
			mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置风格为圆形进度条
			mDialog.setMessage("正在加载 ，请等待...");
			mDialog.setIndeterminate(false);// 设置进度条是否为不明确
			mDialog.setCancelable(true);// 设置进度条是否可以按退回键取消
			mDialog.setCanceledOnTouchOutside(false);
			mDialog.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss(DialogInterface dialog) {
					// TODO Auto-generated method stub
					mDialog = null;
				}
			});
			mDialog.show();

		}
	}

	private void closeProgressDialog() {
		if (mDialog != null) {
			mDialog.dismiss();
			mDialog = null;
		}
	}

	private void deleFile(String caseid, String fileid) {
		if (caseService == null) {
			caseService = new CaseService(getActivity());
		}

		caseService.deleteFile("1", fileid, caseid, id, realname,
				new PostRecordResponseListener() {

					@Override
					public void onFinish(String succString) {
						Intent intent = new Intent();
						intent.setAction(Constant.DELFILE);
						getActivity().sendBroadcast(intent);
						Toast.makeText(getActivity(), succString,
								Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onFailed(String failString) {
						Toast.makeText(getActivity(), failString, Toast.LENGTH_SHORT).show();
					}
				});
	}

	private void initListview(View view) {
		listview = (MyGridView) view.findViewById(R.id.listView_attach);
		adapter = new MyAdapter();
		listview.setAdapter(adapter);
	}

	class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return attchlist.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View view, ViewGroup arg2) {
			View inflate = getActivity().getLayoutInflater().inflate(
					R.layout.list_attach, null);
			TextView tv_file = (TextView) inflate.findViewById(R.id.tv_wenjian);
			TextView tv_person = (TextView) inflate
					.findViewById(R.id.tv_shangchuanren);
			TextView tv_time = (TextView) inflate
					.findViewById(R.id.tv_shangchuantime);

			AttachmentEntity attachmentEntity = attchlist.get(arg0);
			Log.e("caseID", caseID);
			Log.e("attchlist", attchlist.toString());
//			attchlist2.clear();
//			Object[] array = attchlist.toArray();
//			for (int i = array.length - 1; i >= 0; i--) {
//				attchlist2.add((AttachmentEntity) array[i]);
//			}
//			AttachmentEntity attachmentEntity = attchlist2.get(arg0);

			String createtime = attachmentEntity.getCreate_time();
			if ((!("".equals(createtime))) && createtime != null) {
				String month = createtime.substring(4, 6);
				String day = createtime.substring(6, 8);
				String hours = createtime.substring(8, 10);
				String mins = createtime.substring(10, 12);
				String time = month + "-" + day + " " + hours + ":" + mins;
				tv_time.setText(time);
			} else {
				tv_time.setText("");
			}
			tv_file.setText(attachmentEntity.getName());
			tv_person.setText(attachmentEntity.getCreater());
			return inflate;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rela_upload:
			Intent intent = new Intent(getActivity(), UploadFileActivity.class);
			intent.putExtra("caseID", caseID);
			startActivity(intent);
			break;
		default:
			break;
		}

	}

	class MyReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			CaseDetailEntity caseDetailEntity = (CaseDetailEntity) intent.getSerializableExtra("caseDetailEntity");
			caseID = caseDetailEntity.getCid();
			attchlist.clear();
			attchlist = caseDetailEntity.getFiles();
			adapter.notifyDataSetChanged();
		}

	}

}
